package com.asseco.mio.codex.controllers;

import com.asseco.mio.BasicInfo;
import com.asseco.mio.UserInstitution;
import com.asseco.mio.WorkPosition;
import com.asseco.mio.codex.EmploymentReason;
import com.asseco.mio.codex.Institution;
import com.asseco.mio.codex.LeaveReason;
import com.asseco.mio.codex.DeleteReason;
import com.asseco.mio.codex.PosType;
import com.asseco.mio.codex.WorkPositionForm;
import com.asseco.mio.core.model.AuditLog;
import com.asseco.mio.core.webapp.controller.*;
import com.asseco.mio.search.SearchPrijaviOdjavi;
import com.asseco.mio.search.UserSearch;
import com.asseco.persistence.service.HibernateUtil;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.commons.lang.StringUtils;
import org.appfuse.service.GenericManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.appfuse.model.User;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/workpositionformprijava*")
public class WorkPositionFormController extends BaseFormController {

    private String bi1 = "";
    private GenericManager<WorkPosition, String> workPositionManager = null;
    private GenericManager<BasicInfo, String> basicInfoManager = null;
    private GenericManager<Institution, String> institutionManager = null;
    private GenericManager<PosType, String> posTypeManager = null;
    private GenericManager<EmploymentReason, String> employmentReasonManager = null;
    private GenericManager<LeaveReason, String> leaveReasonManager = null;
    private GenericManager<AuditLog, String> auditLoggerManager = null;
    private GenericManager<DeleteReason, String> deleteReasonManager = null;


    public String getBi1() {
        return bi1;
    }

    public void setBi1(String bi1) {
        this.bi1 = bi1;
    }

    @Autowired
    public void setWorkPositionManager(@Qualifier("workPositionManager") GenericManager<WorkPosition, String> workPositionManager) {
        this.workPositionManager = workPositionManager;
    }

    @Autowired
    public void setBasicInfoManager(@Qualifier("basicInfoManager") GenericManager<BasicInfo, String> basicInfoManager) {
        this.basicInfoManager = basicInfoManager;
    }

    @Autowired
    public void setInstitutionManager(@Qualifier("institutionManager") GenericManager<Institution, String> institutionManager) {
        this.institutionManager = institutionManager;
    }

    @Autowired
    public void setPosTypeManager(@Qualifier("posTypeManager") GenericManager<PosType, String> posTypeManager) {
        this.posTypeManager = posTypeManager;
    }

    @Autowired
    public void setEmploymentReasonManager(@Qualifier("employmentReasonManager") GenericManager<EmploymentReason, String> employmentReasonManager) {
        this.employmentReasonManager = employmentReasonManager;
    }

    @Autowired
    public void setLeaveReasonManager(@Qualifier("leaveReasonManager") GenericManager<LeaveReason, String> leaveReasonManager) {
        this.leaveReasonManager = leaveReasonManager;
    }

    @Autowired
    public void setAuditLoggerManager(GenericManager<AuditLog, String> auditLoggerManager) {
        this.auditLoggerManager = auditLoggerManager;
    }
    
    @Autowired
    public void setDeleteReasonManager(GenericManager<DeleteReason, String> deleteReasonManager) {
        this.deleteReasonManager = deleteReasonManager;
    }

    public WorkPositionFormController() {
        setCancelView("redirect:workpositionsearch");
        setSuccessView("redirect:workpositionformprijava");
    }

    @ModelAttribute
    public WorkPositionForm workPositionForm(String bi, User user) {
        
            if (bi == null) {
            if (bi1.equals("")) {
                WorkPositionForm x = new WorkPositionForm(new WorkPosition(), UserInstitution.getInstitutionsForUser(user), getAllActivePosType(this.posTypeManager.getAll()), getAllEmplReason(this.employmentReasonManager.getAll()), getAllLeaveReason(this.leaveReasonManager.getAll()), this.deleteReasonManager.getAll());
                x.setIsEditable(true);
                return x;
            } else {
                WorkPosition wp = new WorkPosition();
                wp.setEmployment(basicInfoManager.get(bi1));
                WorkPositionForm x = new WorkPositionForm(wp, UserInstitution.getInstitutionsForUser(user), getAllActivePosType(this.posTypeManager.getAll()), getAllEmplReason(this.employmentReasonManager.getAll()), getAllLeaveReason(this.leaveReasonManager.getAll()), this.deleteReasonManager.getAll());
                 x.setIsEditable(true);
                return x;
            }
        }
        this.setBi1(bi);
        WorkPosition wp = new WorkPosition();
        wp.setEmployment(basicInfoManager.get(bi1));
        WorkPositionForm x = new WorkPositionForm(wp, UserInstitution.getInstitutionsForUser(user), getAllActivePosType(this.posTypeManager.getAll()), getAllEmplReason(this.employmentReasonManager.getAll()), getAllLeaveReason(this.leaveReasonManager.getAll()), this.deleteReasonManager.getAll());
         x.setIsEditable(true);
        return x;
    }

    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    protected WorkPositionForm showForm(HttpServletRequest request)
            throws Exception {

        String userString = request.getRemoteUser();
        User user = UserSearch.getUserByUserName(userString);

        String id = request.getParameter("idn");
        String bi = request.getParameter("bi");
        WorkPositionForm x = new WorkPositionForm(null, UserInstitution.getInstitutionsForUser(user), getAllActivePosType(this.posTypeManager.getAll()), this.employmentReasonManager.getAll(), getAllLeaveReason(this.leaveReasonManager.getAll()), this.deleteReasonManager.getAll());
        if (!StringUtils.isBlank(id)) {
            x.setWorkPosition(workPositionManager.get(id));
            this.setBi1(x.getWorkPosition().getEmployment().getId());
            x.setIsEditable(SearchPrijaviOdjavi.checkIfLast(x.getWorkPosition()));
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "workpositionform", "workposition.show", x.getWorkPosition().getEmployment().getLastName(),
                    "", request.getRemoteHost(), new Date()));
        }
        if (!StringUtils.isBlank(bi)) {
            x = this.workPositionForm(bi, user);
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "workpositionform", "workposition.show", x.getWorkPosition().getEmployment().getLastName(),
                    "", request.getRemoteHost(), new Date()));
        }
        if (x.getWorkPosition()!=null){
        List institutions = UserInstitution.getInstitutionsForUser(user);
        if (institutions.size()==1){
            x.getWorkPosition().setInstitution((Institution)institutions.get(0));
        }
        }
        return x;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView onSubmit(WorkPositionForm workPositionForm, BindingResult errors, HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {

        String userString = request.getRemoteUser();
        User user = UserSearch.getUserByUserName(userString);
        workPositionForm.setInstitution(UserInstitution.getInstitutionsForUser(user));
        if (request.getParameter("cancel") != null) {
            this.setBi1("");
            response.sendRedirect("workpositionsearch.jsp");
            return new ModelAndView("workpositionsearch", "workpositionList", null);
        }

        log.debug("entering 'onSubmit' method...");

        boolean isNew = (workPositionForm.getWorkPosition().getId().equals(""));
       
        Locale locale = request.getLocale();

        if (!workPositionForm.getSavedReason().getId().equals("")) {
            try{
                workPositionManager.remove(workPositionForm.getWorkPosition().getId());
                saveMessage(request, getText("workPosition.deleted", locale));
                String deleteReasonString = deleteReasonManager.get(workPositionForm.getSavedReason().getId()).toString();

                auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "workpositionform", "workposition.delete", workPositionForm.getWorkPosition().toString(), deleteReasonString, request.getRemoteHost(), new Date()));
                this.setBi1("");
                response.sendRedirect("workpositionsearch.jsp");
            }
            catch (Exception e){
                saveMessage(request, getText("workPosition.Nemoze_da_se_izbrise_zatoa_sto_ima_disciplinska_postapka_ili_ocenuvanje", locale));
                this.setBi1("");
                response.sendRedirect("workpositionsearch.jsp");
            }
        } else {

            WorkPosition x = workPositionForm.getWorkPosition();
            x.setEmployment(basicInfoManager.get(bi1));
            Session session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            String pamFirstName = x.getEmployment().getFirstName();
            String pamLastName = x.getEmployment().getLastName();
            String pamSocScrNo = x.getEmployment().getSocScrNo();
            Query q = session.createQuery("from WorkPosition workPos inner join workPos.employment where  "
                    + "workPos.employment.firstName like '" + pamFirstName + "' and "
                    + "workPos.employment.lastName like '" + pamLastName + "' and "
                    + "workPos.employment.socScrNo like '" + pamSocScrNo + "' order by workPos.startDate desc limit 1 ");


            List tempResult = q.list();
            List result = new ArrayList();
            for (int j = 0; j < tempResult.size(); j++) {
                Object[] object = (Object[]) tempResult.get(j);
                WorkPosition workPos = (WorkPosition) object[0];
                result.add(workPos);
            }
            session.getTransaction().commit();
            if (result.isEmpty()) {
                Calendar startDate = Calendar.getInstance();
                startDate.setTime(x.getStartDate());
                Calendar currentDate = Calendar.getInstance();
                Calendar tempCurrentDate = Calendar.getInstance();
                tempCurrentDate.add(currentDate.DATE, -15);

                DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
                Date trashold1 = formatter.parse("24/04/2011");
                Calendar trashold = Calendar.getInstance();trashold.setTime(trashold1);
                if(startDate.before(trashold)){
                    saveMessage(request, getText("workPosition.DatumotNaPrijavaEPredDatumotKogaEDonesenZakonot", locale));
                    return new ModelAndView("workpositionformprijava", "workPositionForm", workPositionForm);
                }
                if(currentDate.before(startDate)){
                    saveMessage(request, getText("workPosition.NemozeDaSeNapraviPrijavaZaVoIdnina", locale));
                    return new ModelAndView("workpositionformprijava", "workPositionForm", workPositionForm);
                }

                if (startDate.before(tempCurrentDate)) {
                    
                        workPositionManager.save(x);
                        String key = (isNew) ? "workPosition.added" : "workPosition.updated";
                        saveMessage(request, getText(key, locale));
                        auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "workpositionform", key, workPositionForm.getWorkPosition().getEmployment().getLastName(),
                                "", request.getRemoteHost(), new Date()));
                        saveMessage(request, getText("workPosition.DatumotNaPrijavaEPredPovekeOd2Nedeli", locale));
                        this.setBi1("");
                        workPositionForm.setWorkPosition(null);
                        return new ModelAndView("workpositionsearch", "workpositionList", null);
                } else {
                    workPositionManager.save(x);
                    String key = (isNew) ? "workPosition.added" : "workPosition.updated";
                    saveMessage(request, getText(key, locale));
                    auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "workpositionform", key, workPositionForm.getWorkPosition().getEmployment().getLastName(),
                            "", request.getRemoteHost(), new Date()));
                    this.setBi1("");
                    response.sendRedirect("workpositionsearch.jsp");
                }
            } else {
                WorkPosition position = (WorkPosition) result.get(0);
                String discriminator = position.getDiscriminator();
                if (discriminator.equals("0")) {

                    Calendar startDate = Calendar.getInstance();
                    startDate.setTime(x.getStartDate());
                    Calendar oldStartDate = Calendar.getInstance();
                    oldStartDate.setTime(position.getStartDate());
                    Calendar currentDate = Calendar.getInstance();
                    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
                Date trashold1 = formatter.parse("24/04/2011");
                Calendar trashold = Calendar.getInstance();trashold.setTime(trashold1);
                if(startDate.before(trashold)){
                    saveMessage(request, getText("workPosition.DatumotNaPrijavaEPredDoneseniotZakon", locale));
                    return new ModelAndView("workpositionformprijava", "workPositionForm", workPositionForm);
                }
                if(currentDate.before(startDate)){
                    saveMessage(request, getText("workPosition.NemozeDaSeNapraviPrijavaZaVoIdnina", locale));
                    return new ModelAndView("workpositionformprijava", "workPositionForm", workPositionForm);
                }

                    if (startDate.before(oldStartDate)||startDate.equals(oldStartDate)) {

                        saveMessage(request, getText("workPosition.ENaIliPredDatumotNaOdjava", locale));
                        return new ModelAndView("workpositionformprijava", "workPositionForm", workPositionForm);
                    } else {
                        Calendar tempCurrentDate = Calendar.getInstance();
                        tempCurrentDate.add(currentDate.DATE, -15);
                        if (startDate.before(tempCurrentDate)) {
                            workPositionManager.save(x);
                                String key = (isNew) ? "workPosition.added" : "workPosition.updated";
                                saveMessage(request, getText(key, locale));
                                 saveMessage(request, getText("workPosition.DatumotNaPrijavaEPredPovekeOd2Nedeli", locale));
                                 this.setBi1("");
                                 workPositionForm.setWorkPosition(null);
                                return new ModelAndView("workpositionsearch", "workpositionList", null);
                                
                            
                        } else {
                            workPositionManager.save(x);
                            String key = (isNew) ? "workPosition.added" : "workPosition.updated";
                            saveMessage(request, getText(key, locale));
                            this.setBi1("");
                            response.sendRedirect("workpositionsearch.jsp");
                        }
                    }
                } else {
                    if(workPositionForm.getWorkPosition().getId().equals("")){
                        saveMessage(request, getText("workPosition.ImaAktivnaPrijava", locale));
                        this.setBi1(bi1);
                        response.sendRedirect("workpositionsearch.jsp");
                    }
                  else{
                      

                      Calendar startDate = Calendar.getInstance();
                    startDate.setTime(x.getStartDate());
                    Calendar oldStartDate = Calendar.getInstance();
                    oldStartDate.setTime(position.getStartDate());
                    Calendar currentDate = Calendar.getInstance();
                    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
                Date trashold1 = formatter.parse("24/04/2011");
                Calendar trashold = Calendar.getInstance();trashold.setTime(trashold1);

                      if(startDate.before(trashold)){
                    saveMessage(request, getText("workPosition.DatumotNaPrijavaEPredDoneseniotZakon", locale));
                    return new ModelAndView("workpositionformprijava", "workPositionForm", workPositionForm);
                }
                if(currentDate.before(startDate)){
                    saveMessage(request, getText("workPosition.NemozeDaSeNapraviPrijavaZaVoIdnina", locale));
                    return new ModelAndView("workpositionformprijava", "workPositionForm", workPositionForm);
                }

                    if (startDate.before(oldStartDate)) {

                        session.beginTransaction();

            Query qq = session.createQuery("from WorkPosition workPos inner join workPos.employment where  "
                    + " workPos.employment.firstName like '" + pamFirstName + "' and "
                    + " workPos.employment.lastName like '" + pamLastName + "' and "
                    + " workPos.discriminator like '"+ 0 +"' and"
                    + " workPos.employment.socScrNo like '" + pamSocScrNo + "' order by workPos.startDate desc limit 1 ");


            List tempResult1 = qq.list();
            List result1 = new ArrayList();
            for (int j = 0; j < tempResult1.size(); j++) {
                Object[] object = (Object[]) tempResult1.get(j);
                WorkPosition workPos = (WorkPosition) object[0];
                result1.add(workPos);
            }
            session.getTransaction().commit();

                    if(result1.isEmpty()){
                        workPositionManager.save(x);
                                String key = (isNew) ? "workPosition.added" : "workPosition.updated";
                                saveMessage(request, getText(key, locale));
                                 this.setBi1("");
                                 workPositionForm.setWorkPosition(null);
                                 return new ModelAndView("workpositionsearch", "workpositionList", null);
                    }
                    else{
                        WorkPosition pospos = (WorkPosition) result1.get(0);
                        Calendar odjavaoldStartDate = Calendar.getInstance();
                        odjavaoldStartDate.setTime(pospos.getStartDate());
                        if(startDate.before(odjavaoldStartDate)||startDate.equals(odjavaoldStartDate)){
                            saveMessage(request, getText("workPosition.ENaIliPredDatumotNaOdjava", locale));
                            return new ModelAndView("workpositionformprijava", "workPositionForm", workPositionForm);
                        }
                        else{
                            String key = (isNew) ? "workPosition.added" : "workPosition.updated";
                                saveMessage(request, getText(key, locale));
                                 this.setBi1("");
                                 workPositionForm.setWorkPosition(null);
                                 return new ModelAndView("workpositionsearch", "workpositionList", null);
                        }


                        
                    }} else {
                        Calendar tempCurrentDate = Calendar.getInstance();
                        tempCurrentDate.add(currentDate.DATE, -15);
                        if (startDate.before(tempCurrentDate)) {
                            workPositionManager.save(x);
                                String key = (isNew) ? "workPosition.added" : "workPosition.updated";
                                saveMessage(request, getText(key, locale));
                                 saveMessage(request, getText("workPosition.DatumotNaPrijavaEPredPovekeOd2Nedeli", locale));
                                 this.setBi1("");
                                 workPositionForm.setWorkPosition(null);
                                 return new ModelAndView("workpositionsearch", "workpositionList", null);


                        } else {
                            workPositionManager.save(x);
                            String key = (isNew) ? "workPosition.added" : "workPosition.updated";
                            saveMessage(request, getText(key, locale));
                            this.setBi1(bi1);
                            response.sendRedirect("workpositionsearch.jsp");
                        }
                  }

                }
            }
            if (!isNew) {
                return new ModelAndView("workpositionformprijava", "workPositionForm", workPositionForm);
            }
        }}
        return new ModelAndView("workpositionsearch", "workPositionForm", workPositionForm);
    
    }
    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        super.initBinder(request, binder);
        SimpleDateFormat dateFormat =
                new SimpleDateFormat(getText("dd/MM/yyyy", request.getLocale()));
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(dateFormat, true));
    }

    public List getAllActiveInstitutions(List<Institution> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            Institution ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }

    public List getAllActivePosType(List<PosType> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            PosType ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }

    public List getAllEmplReason(List<EmploymentReason> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            EmploymentReason ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }

    public List getAllLeaveReason(List<LeaveReason> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            LeaveReason ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }
}
